#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
挂机管理器
负责挂机逻辑和奖励计算
"""

import time
from typing import Dict, Any, List, Tuple, Optional
from character.character import Character

class IdleManager:
    """
    挂机管理器
    """
    
    def __init__(self):
        """
        初始化挂机管理器
        """
        # 定义挂机地点和对应的奖励倍率
        self.idle_locations = {
            "新手村": {
                "name": "新手村",
                "description": "适合新手的安全地带",
                "exp_multiplier": 1.0,
                "min_level": 1,
                "max_level": 10
            },
            "森林": {
                "name": "森林",
                "description": "茂密的森林，经验获取稍快",
                "exp_multiplier": 1.5,
                "min_level": 5,
                "max_level": 20
            },
            "山洞": {
                "name": "山洞",
                "description": "危险的山洞，经验丰富",
                "exp_multiplier": 2.0,
                "min_level": 15,
                "max_level": 35
            },
            "古战场": {
                "name": "古战场",
                "description": "充满战斗气息的古老战场",
                "exp_multiplier": 3.0,
                "min_level": 30,
                "max_level": 50
            },
            "魔法塔": {
                "name": "魔法塔",
                "description": "神秘的魔法塔，高级挂机地点",
                "exp_multiplier": 4.0,
                "min_level": 45,
                "max_level": 999
            }
        }
        
        print("挂机管理器初始化完成")
    
    def get_available_locations(self, character: Optional[Character] = None) -> List[Dict[str, Any]]:
        """
        获取可用的挂机地点
        
        Args:
            character: 角色对象，用于过滤适合的地点
            
        Returns:
            可用地点列表
        """
        available = []
        
        for location_id, location_data in self.idle_locations.items():
            location_info = location_data.copy()
            location_info['id'] = location_id
            
            # 如果提供了角色，检查等级要求
            if character:
                if character.level < location_data['min_level']:
                    location_info['available'] = False
                    location_info['reason'] = f"需要等级 {location_data['min_level']}"
                elif character.level > location_data['max_level']:
                    location_info['available'] = False
                    location_info['reason'] = "等级过高，经验获取效率低"
                else:
                    location_info['available'] = True
                    location_info['reason'] = "可用"
            else:
                location_info['available'] = True
                location_info['reason'] = "可用"
            
            available.append(location_info)
        
        return available
    
    def start_idle(self, character: Character, location: str) -> Tuple[bool, str]:
        """
        开始挂机
        
        Args:
            character: 角色对象
            location: 挂机地点
            
        Returns:
            (成功标志, 消息)
        """
        if character.is_idle:
            return False, f"{character.name} 已经在挂机中"
        
        if character.is_in_battle:
            return False, f"{character.name} 正在战斗中，无法挂机"
        
        # 检查地点是否存在
        if location not in self.idle_locations:
            return False, f"挂机地点 '{location}' 不存在"
        
        location_data = self.idle_locations[location]
        
        # 检查等级要求
        if character.level < location_data['min_level']:
            return False, f"等级不足，需要等级 {location_data['min_level']}"
        
        # 开始挂机
        success, message = character.start_idle(location)
        
        if success:
            return True, f"{character.name} 开始在 {location_data['name']} 挂机"
        else:
            return False, message
    
    def stop_idle(self, character: Character) -> Tuple[bool, str, Dict[str, Any]]:
        """
        停止挂机
        
        Args:
            character: 角色对象
            
        Returns:
            (成功标志, 消息, 奖励信息)
        """
        if not character.is_idle:
            return False, f"{character.name} 未在挂机状态", {}
        
        # 计算挂机奖励
        rewards = self.calculate_idle_rewards(character)
        
        # 停止挂机
        success, message = character.stop_idle()
        
        if success:
            reward_text = self._format_rewards(rewards)
            full_message = f"{message}\n获得奖励: {reward_text}"
            return True, full_message, rewards
        else:
            return False, message, {}
    
    def calculate_idle_rewards(self, character: Character) -> Dict[str, Any]:
        """
        计算挂机奖励
        
        Args:
            character: 角色对象
            
        Returns:
            奖励信息
        """
        if not character.is_idle or not character.idle_start_time:
            return {}
        
        idle_duration = time.time() - character.idle_start_time
        idle_hours = idle_duration / 3600
        
        # 获取地点信息
        location_data = self.idle_locations.get(character.idle_location, {})
        exp_multiplier = location_data.get('exp_multiplier', 1.0)
        
        # 基础经验：每小时10经验
        base_exp_per_hour = 10
        
        # 等级加成：等级越高基础经验越多
        level_bonus = 1 + (character.level - 1) * 0.1
        
        # 计算总经验
        total_exp = int(idle_hours * base_exp_per_hour * exp_multiplier * level_bonus)
        
        # 确保至少获得1点经验（如果挂机时间超过6分钟）
        if idle_duration > 360 and total_exp == 0:
            total_exp = 1
        
        return {
            'exp': total_exp,
            'idle_duration': idle_duration,
            'idle_hours': idle_hours,
            'location': character.idle_location,
            'exp_multiplier': exp_multiplier,
            'level_bonus': level_bonus
        }
    
    def get_idle_status(self, character: Character) -> Optional[Dict[str, Any]]:
        """
        获取角色的挂机状态
        
        Args:
            character: 角色对象
            
        Returns:
            挂机状态信息
        """
        if not character.is_idle:
            return None
        
        idle_duration = time.time() - character.idle_start_time
        location_data = self.idle_locations.get(character.idle_location, {})
        
        # 计算当前可获得的奖励
        current_rewards = self.calculate_idle_rewards(character)
        
        return {
            'is_idle': True,
            'location': character.idle_location,
            'location_name': location_data.get('name', character.idle_location),
            'start_time': character.idle_start_time,
            'duration': idle_duration,
            'current_rewards': current_rewards
        }
    
    def _format_rewards(self, rewards: Dict[str, Any]) -> str:
        """
        格式化奖励信息为字符串
        
        Args:
            rewards: 奖励信息
            
        Returns:
            格式化的奖励字符串
        """
        if not rewards:
            return "无"
        
        parts = []
        
        if rewards.get('exp', 0) > 0:
            parts.append(f"经验 +{rewards['exp']}")
        
        if rewards.get('idle_duration', 0) > 0:
            duration = rewards['idle_duration']
            if duration >= 3600:
                hours = int(duration // 3600)
                minutes = int((duration % 3600) // 60)
                parts.append(f"挂机时长 {hours}小时{minutes}分钟")
            elif duration >= 60:
                minutes = int(duration // 60)
                seconds = int(duration % 60)
                parts.append(f"挂机时长 {minutes}分钟{seconds}秒")
            else:
                parts.append(f"挂机时长 {duration:.1f}秒")
        
        return ", ".join(parts) if parts else "无"